<template>
  <div class="conversation-page">
    <FirstPart ref="firstPart" />
    <SecondPart ref="secondPart" />
    <ThirdPart ref="thirdPart" />

    <!-- 快速发朋友圈 -->
    <div id="draggableWrap" draggable="true" @dragend="endMove($event)">
      <template v-if="!chatListVisible && !screenCaptrueVisible">
        <!-- 聚合朋友圈 -->
        <svg
          class="icon"
          style="font-size: 30px; cursor: pointer; margin: 5px 0"
          aria-hidden="true"
          @click="showScreenCap($event)"
        >
          <use xlink:href="#iconxianxingmofang"></use>
        </svg>
        <svg
          v-if="!chatListVisible"
          class="icon"
          style="font-size: 30px; cursor: pointer"
          aria-hidden="true"
          @click="showChatList($event)"
        >
          <use xlink:href="#icon-friend-circle"></use>
        </svg>
      </template>

      <div
        v-if="chatListVisible"
        style="width: 800px; height: 500px; background-color: #fff; border: solid #dbdbdb 1px"
      >
        <div class="tip">
          <span style="font-size: 16px; font-weight: 600">待发朋友圈列表</span>
          <i class="el-icon-close" style="cursor: pointer; font-size: 20px" @click="hideChatList"></i>
        </div>
        <el-table :data="chatMsgData" style="width: 800px" height="460px" stripe border>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="textContent" label="内容"></el-table-column>
          <el-table-column prop="media" label="媒体">
            <template slot-scope="scope">
              <img
                v-for="(imgUrl, index) in scope.row.media"
                :key="index"
                style="height: 100px; width: 100px; object-fit: cover"
                :src="imgUrl"
              />
            </template>
          </el-table-column>
          <el-table-column prop="media" label="客户">
            <template slot-scope="scope">

              <div class="goFriend" @click="goFriend(scope.row)"  target="_blank" >
                <div class="head"><img :src="scope.row.Avatar"></div>
                <div class="name">{{ scope.row.FriendNick }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="140">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="sendChatItem(scope.row)">发送</el-button>
              <el-button type="text" size="small" @click="deleteChatItem(scope.row)">删除</el-button>
              <el-button type="text" size="small" @click="insertLocalStorage(scope.row)">存草稿</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div
        v-if="screenCaptrueVisible"
        style="width: 900px; height: 500px; background-color: #fff; border: solid #dbdbdb 1px"
      >
        <div class="tip">
          <span style="font-size: 16px; font-weight: 600">九宫格朋友圈</span>
          <i class="el-icon-close" style="cursor: pointer; font-size: 20px" @click="hideChatList"></i>
        </div>
        <div style="width: 100%; height: 460px; padding: 5px; display: flex; overflow: hidden">
          <div class="scroll tab-list">
            <div
              v-for="(tab, tabIndex) in circleTabs"
              :key="tabIndex"
              class="tab-item"
              :class="[{ 'current-tab': currentTab === tabIndex }]"
              @click="currentTab = tabIndex"
            >
              <span v-text="tab"></span>
              <div v-if="screenUrl[tabIndex] && screenUrl[tabIndex].length > 0" class="has-img"></div>
            </div>
          </div>

          <el-input
            v-model="screenText[currentTab]"
            style="width: 300px; height: 100%"
            type="textarea"
            :resize="'none'"
            placeholder="请输入内容"
          ></el-input>

          <div
            style="
              width: 485px;
              height: 100%;
              border: solid #edeff3 1px;
              margin-left: 5px;
              border-radius: 5px;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              overflow: auto;
            "
          >
            <div style="display: flex; flex-wrap: wrap">
              <div v-for="(sl, slindex) in screenUrl[currentTab]" :key="slindex" class="img-box">
                <el-image style="width: 120px; height: 120px" :src="sl" fit="cover"></el-image>
                <i class="el-icon-delete delete-icon" @click="deleteImg(slindex)"></i>
                <i class="el-icon-place place-icon" @click="insertImg(slindex)"></i>
                <i class="el-icon-sort sort-icon" @click="exchangeImg(slindex)"></i>
                <i class="el-icon-rank rank-icon" @click="showBigImg(sl)"></i>
              </div>
            </div>

            <div style="margin-top: 10px; align-self: center">
              <el-button icon="el-icon-plus" @click="fetchScreenShot">添加图片</el-button>
              <el-button @click="sendScreenShot">立即发送</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 服务端保存的截图 -->
    <el-dialog title="截屏列表" class="we-app we-app-big" append-to-body :visible.sync="dialogVisible">
      <div
        v-for="(rItem, rindex) in resourcesDataList"
        :key="rindex"
        class="we-app-item screen-shot-item"
        :class="{ 'we-app-item-checked': choseId.indexOf(rItem.id) >= 0 }"
        @click="choseScreenShot(rItem.id)"
      >
        <el-image style="width: 200px; height: 200px" :src="rItem.content" fit="cover"></el-image>
        <i class="el-icon-delete" @click="deleteSSR(rItem.id)"></i>
      </div>

      <!-- 分页 -->
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageSizes="[9, 18]"
        :page.sync="page"
        :limit.sync="limit"
        @pagination="fetchScreenShot"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addImg2ScreenShot">确 定</el-button>
      </span>
    </el-dialog>

    <div class="demo-image__preview big-img-box">
      <el-image
        id="bigImageBox2"
        style="width: 100px; height: 100px"
        :src="bigImgUrl"
        :preview-src-list="[bigImgUrl]"
      ></el-image>
    </div>
  </div>
</template>

<script>
import FirstPart from './components/first/index.vue'
import SecondPart from './components/second/index.vue'
import ThirdPart from './components/third/index.vue'
import { GetWeChatsReq, resourcesList, deleteResources } from '@/api/httpApi'
import { uniqueArryList } from '@/utils/util'
import Pagination from '@/components/Pagination'
import { TriggerConversationPushTask } from '@/api/webSocketApi'

import { mapGetters } from 'vuex'
import bus from '@/utils/bus'

export default {
  name: 'ConversationPage',
  components: {
    FirstPart,
    SecondPart,
    ThirdPart,
    Pagination
  },
  data() {
    return {
      routerViewName: 'conversation',
      chatListVisible: false, // 快速发送朋友圈
      screenCaptrueVisible: false, // 展示截屏
      resourcesDataList: [], // 服务端保存的截屏
      dialogVisible: false,
      choseId: [],
      page: 1,
      limit: 9,
      total: 0,
      bigImgUrl: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      srcList: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
      ],
      baseText: '【p1】\n【p2】\n【p3】\n【p4】\n【p5】',
      screenText: [],
      screenUrl: [],
      currentTab: 0,
      circleTabs: []
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      chatList: 'circleManager/chatList',
      currentWechat: 'conversation/currentWechat',
      currentWeChatId: 'conversation/currentWeChatId',
      currentFriendId: 'conversation/currentFriendId',
      screenTextCache: 'conversation/screenText',
      screenUrlCache: 'conversation/screenUrl'
    }),
    // 重组数据
    chatMsgData() {
      const td = []
      const tdMap = {}
      console.log(this.chatList);
      for (const cl of this.chatList) {
        const tid = cl.WeChatId + cl.FriendId
        if (tdMap[tid]) {
          for (const ti of td) {
            if (ti.id === tid) {
              if (cl.ContentType === 'Text') {
                ti.textContent = ti.textContent ? ti.textContent + ' ' + cl.Content : cl.Content
              } else if (cl.ContentType === 'Picture') {
                if (cl.Url) {
                  if (ti.media) {
                    ti.media.push(cl.Url)
                  } else {
                    ti.media = [cl.Url]
                  }
                } else {
                  const thumbImg = JSON.parse(cl.Content).Thumb
                  if (ti.media) {
                    ti.media.push(thumbImg)
                  } else {
                    ti.media = [thumbImg]
                  }
                }
              }
              break
            }
          }
        } else {
          tdMap[tid] = true
          const circleObj = cl
          circleObj.id = cl.WeChatId + cl.FriendId
          if (cl.ContentType === 'Text') {
            circleObj.textContent = cl.Content
          } else if (cl.ContentType === 'Picture') {
            if (cl.Url) {
              circleObj.media = [cl.Url]
            } else {
              circleObj.media = [JSON.parse(cl.Content).Thumb]
            }
          }
          td.push(circleObj)
        }
      }
      return td
    }
  },
  mounted() {
    var jump=this.$route.query.jump;
    if(jump){
      let j=JSON.parse(jump);
      this.$parent.$parent.gouser(j.wxid);
      TriggerConversationPushTask(j.wxid, 0);
      this.goFriendbyId(j.fid);
    }
    GetWeChatsReq(this.currentUser.UnionId).then((res) => {
      if (res.code === 0 && res.data) {
        const wechatsList = []
        for (const wechatObj of res.data) {
          const nwo = {}
          for (const key in wechatObj) {
            if (Object.hasOwnProperty.call(wechatObj, key)) {
              // const element = object[key];
              if (key === 'avatar') {
                nwo['Avatar'] = wechatObj.avatar
              } else if (key === 'isonline') {
                nwo['IsOnline'] = wechatObj.isonline === 0
              } else if (key === 'wechatno') {
                nwo['WeChatNo'] = wechatObj.wechatno
              } else if (key === 'wechatnick') {
                nwo['WeChatNick'] = wechatObj.wechatnick
              } else if (key === 'wechatid') {
                nwo['WeChatId'] = wechatObj.wechatid
              } else {
                nwo[key] = wechatObj[key]
              }
            }
          }
          wechatsList.push(nwo)
        }
        this.$store.commit('conversation/SET_WECHATS', wechatsList)

        let ww = []
        for (const wechat of wechatsList) {
          if (wechat.WeChatNick) {
            ww.push(wechat.WeChatNick.slice(0, 4))
          }
        }
        ww = [...new Set(ww)]
        this.circleTabs = ww
        for (let index = 0; index < ww.length; index++) {
          this.screenText[index] = this.baseText
          this.screenUrl[index] = []
        }
        if (this.screenTextCache.length > 0) {
          this.screenText = this.screenTextCache
        }
        if (this.screenUrlCache.length > 0) {
          this.screenUrl = this.screenUrlCache
        }
      }
    })
  },
  beforeDestroy() {
    this.$store.commit('conversation/SET_SCREEN_TEXT', this.screenText)
    this.$store.commit('conversation/SET_SCREEN_URL', this.screenUrl)
  },
  methods: {
    goFriend(row){
      if (this.$refs.firstPart) {
        this.$refs.firstPart.choseFriend(row)
      } else {
        console.warn('firstPart 组件尚未挂载')
      }
    },
    goFriendbyId(id){
      if (this.$refs.firstPart) {
        this.$refs.firstPart.choseFriendById(id)
      } else {
        console.warn('firstPart 组件尚未挂载')
      }
    },
    // 修改朋友圈列表的位置
    endMove(e) {
      const dwDom = document.getElementById('draggableWrap')
      if (dwDom) {
        dwDom.style.left = e.clientX + 'px'
        dwDom.style.top = e.clientY + 'px'
      }
    },
    // 展示截屏
    showScreenCap(e) {
      const fid = this.circleTabs.findIndex((x) => {
        return this.currentWechat.WeChatNick && x === this.currentWechat.WeChatNick.slice(0, 4)
      })
      this.currentTab = fid

      const dwDom = document.getElementById('draggableWrap')
      if (dwDom) {
        dwDom.style.left = e.clientX / 2 - 400 + 'px'
        dwDom.style.top = e.clientY / 2 - 250 + 'px'
      }
      this.screenCaptrueVisible = true
      // 阻止enter发消息
      bus.$emit('toggleEnterSend', false)
    },
    // 展示列表
    showChatList(e) {
      const dwDom = document.getElementById('draggableWrap')
      if (dwDom) {
        dwDom.style.left = e.clientX / 2 - 400 + 'px'
        dwDom.style.top = e.clientY / 2 - 250 + 'px'
      }
      this.chatListVisible = !this.chatListVisible
    },
    // 隐藏列表
    hideChatList() {
      const dwDom = document.getElementById('draggableWrap')
      if (dwDom) {
        dwDom.style.left = window.innerWidth - 100 + 'px'
        dwDom.style.top = window.innerHeight - 120 + 'px'
      }
      this.chatListVisible = false
      this.screenCaptrueVisible = false
      bus.$emit('toggleEnterSend', true)
    },
    // 删除图片
    deleteImg(index) {
      // this.$store.commit('conversation/REMOVE_IMG', index)
      this.screenUrl[this.currentTab].splice(index, 1)
      this.$forceUpdate()
    },
    // 插入图片
    insertImg(index) {
      this.$prompt('请输入要插入的位置', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]+$/,
        inputErrorMessage: '请输入正整数'
      })
        .then(({ value }) => {
          const ti = Number(value)
          const ta = this.screenUrl[this.currentTab]
          if (ti >= 1 && ti <= ta.length) {
            // this.$store.commit('conversation/INSERT_IMG', { ci: index, ti: value })
            if (index === ti - 1) return
            if (index > ti - 1) {
              ta.splice(ti - 1, 0, ta[index])
              ta.splice(index + 1, 1)
            } else {
              ta.splice(ti, 0, ta[index])
              ta.splice(index, 1)
            }
            this.$forceUpdate()
          } else {
            this.$message.warning('无效的位置')
          }
        })
        .catch(() => {})
    },
    // 交换图片位置
    exchangeImg(index) {
      this.$prompt('请输入要交换的位置', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]+$/,
        inputErrorMessage: '请输入正整数'
      })
        .then(({ value }) => {
          const ti = Number(value)
          const ta = this.screenUrl[this.currentTab]

          if (ti >= 1 && ti <= ta.length) {
            // this.$store.commit('conversation/EXCHANGE_IMG', { ci: index, ti: value })
            if (index === ti - 1) return
            const exchangeP = JSON.parse(JSON.stringify(ta[index]))
            ta.splice(index, 1, ta[ti - 1])
            ta.splice(ti - 1, 1, exchangeP)

            this.$forceUpdate()
          } else {
            this.$message.warning('无效的位置')
          }
        })
        .catch(() => {})
    },
    // 展示大图
    showBigImg(imgUrl) {
      this.bigImgUrl = imgUrl
      const imgDom = document.getElementById('bigImageBox2')
      setTimeout(() => {
        if (imgDom) {
          imgDom.click()
        }
      }, 100)
    },
    // 从服务端拉去截图
    fetchScreenShot() {
      resourcesList(this.currentUser.SupplierId, this.page, this.limit, 100)
        .then((res) => {
          if (res.code === 0 && res.data.rows) {
            this.resourcesDataList = res.data.rows
            this.total = res.data.records || 0
          } else {
            this.resourcesDataList = []
            this.total = 0
          }
          this.dialogVisible = true
        })
        .catch((err) => {
          this.$alert(err, '提示', { type: 'warning' })
        })
    },
    // 选择截图
    choseScreenShot(rid) {
      const fi = this.choseId.findIndex((x) => {
        return x === rid
      })
      if (fi === -1) {
        this.choseId.push(rid)
      } else {
        this.choseId.splice(fi, 1)
      }
    },
    // 从服务端删除截图
    deleteSSR(resourceId) {
      deleteResources(resourceId)
        .then((res) => {
          if (res.code === 0) {
            this.fetchScreenShot()
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 将图片弄到截屏
    addImg2ScreenShot() {
      for (const rd of this.resourcesDataList) {
        if (this.choseId.indexOf(rd.id) >= 0) {
          // this.$store.commit('conversation/SAVE_SCREEN_SHOT', { Url: rd.content, hideMessage: true })
          this.screenUrl[this.currentTab].push(rd.content)
        }
      }
      this.dialogVisible = false
    },
    // 删除待发朋友圈
    deleteChatItem(chat) {
      console.log(chat);
      this.$store.commit('circleManager/DELETE_CHAT_LIST_BY_ID', chat.id)
      // 删除本地保存的数据
      const cll = localStorage.getItem('chatListLocal')
      if (cll) {
        const jcll = JSON.parse(cll)
        const njcll = jcll.filter((x) => {
          return chat.id !== x.WeChatId + x.FriendId
        })
        localStorage.setItem('chatListLocal', JSON.stringify(njcll))
      }
    },
    // 发送截图朋友圈
    sendScreenShot() {
      this.sendChatItem({
        media: this.screenUrl[this.currentTab],
        textContent: this.screenText[this.currentTab],
      })
      // 立即发送后 还原数据
      this.screenText[this.currentTab] = '【p1】\n【p2】\n【p3】\n【p4】\n【p5】'
      this.screenUrl[this.currentTab] = []
    },
    // 跳转到发朋友圈页面
    sendChatItem(chat) {
      this.$store.commit('circleManager/SET_CIRCLE_2_SEND', chat)
      this.$router.push({ path: '/circleManager' })
      this.$store.commit('circleManager/SET_CURRENT_CIRLCLE_NAV', 'sendCircle')
    },
    // 存为草稿
    insertLocalStorage(row) {
      const msg2save = this.chatList.filter((x) => {
        x.circleId = x.WeChatId + x.FriendId
        return x.WeChatId + x.FriendId === row.id
      })
      const cll = localStorage.getItem('chatListLocal')
      if (cll) {
        const jcll = JSON.parse(cll)
        const njcll = uniqueArryList(jcll.concat(msg2save), 'MsgSvrId')
        localStorage.setItem('chatListLocal', JSON.stringify(njcll))
      } else {
        localStorage.setItem('chatListLocal', JSON.stringify(msg2save))
      }
      this.$message.success('存为草稿成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.big-img-box {
  position: absolute;
  top: 0;
  right: -200px;
}

.conversation-page {
  flex: 1 1 auto;
  display: flex;
  justify-content: space-between;
  // position: relative;

  #draggableWrap {
    display: flex;
    flex-direction: column;

    position: absolute;
    top: calc(100vh - 120px);
    left: calc(100vw - 100px);
    z-index: 1001;
    // max-width: 800px;
    // border: solid red 1px;
    .tip {
      background: #fff;
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 10px;
    }
  }
}
.img-box {
  position: relative;
  width: 150px;
  height: 130px;
  display: flex;
  align-items: center;
  justify-content: center;
  .delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    color: red;
    cursor: pointer;
  }
  .place-icon {
    position: absolute;
    top: 20px;
    right: 0;
    color: #409eff;
    cursor: pointer;
  }
  .sort-icon {
    position: absolute;
    top: 40px;
    right: 0;
    color: #409eff;
    cursor: pointer;
  }
  .rank-icon {
    position: absolute;
    top: 60px;
    right: 0;
    color: #409eff;
    cursor: pointer;
  }
}

.tab-list {
  width: 100px;
  height: 450px;
  overflow: auto;

  .tab-item {
    padding: 10px;
    cursor: pointer;
    position: relative;

    .has-img {
      height: 10px;
      width: 10px;
      border-radius: 5px;
      background-color: red;
      position: absolute;
      top: 5px;
      right: 10px;
    }
  }

  .current-tab {
    color: #409eff;
  }
}

::v-deep .el-textarea__inner {
  height: 100%;
}
.goFriend{
  display: flex;
  flex-direction: row;
  color: #409eff;
  .head{
    width: 30px;
    margin: 0px 10px;
  }
  .name{
    line-height: 30px;
  }
}
.goFriend:hover{
  text-decoration: underline;
  cursor: pointer;
  color: #409eff;
}
</style>
